package demo.base;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 将字符串模板中包含的{{varname}}或{varname}替换成其他值
 */
public class Template {

    public static enum TemplateType {
        SINGLE,
        DOUBLE
    }

    private boolean throwExceptionIfVarNotExist = true;
    private String content;
    private TemplateType type;

    public Template(String content, TemplateType type) {
        this.content = content;
        this.type = type;
    }

    public boolean isThrowExceptionIfVarNotExist() {
        return throwExceptionIfVarNotExist;
    }

    public void setThrowExceptionIfVarNotExist(boolean throwExceptionIfVarNotExist) {
        this.throwExceptionIfVarNotExist = throwExceptionIfVarNotExist;
    }

    public String format(Map<String, String> map) {

        String regex = null;
        String start = "";
        String end = "";
        switch (type){
            case SINGLE:
                start = "{";
                end = "}";
                regex = "\\{[^\\{]*?\\}";
                break;
            case DOUBLE:
                start = "{{";
                end = "}}";
                regex = "\\{\\{[^\\{]*?\\}\\}";
                break;
        }

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(this.content);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String indexStringWithBracket = matcher.group();
            String indexString = StringUtils.removeStartEnd(indexStringWithBracket, start, end);

            if (map.containsKey(indexString)) {
                String replacement = map.get(indexString);
                matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
            } else {
                if (throwExceptionIfVarNotExist) {
                    throw new VarNotFoundException("找不到变量" + indexString);
                } else {
                    String replacement = "";
                    matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
                }
            }
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    public static class VarNotFoundException extends RuntimeException {

        public VarNotFoundException() {
            super();
        }

        public VarNotFoundException(String message, Throwable cause,
                                    boolean enableSuppression, boolean writableStackTrace) {
            super(message, cause, enableSuppression, writableStackTrace);
        }

        public VarNotFoundException(String message, Throwable cause) {
            super(message, cause);
        }

        public VarNotFoundException(String message) {
            super(message);
        }

        public VarNotFoundException(Throwable cause) {
            super(cause);
        }

    }


}
